/*
 * Copyright (C) 2014 VenomVendor <info@VenomVendor.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.naizhuai.ui.adapter;

import com.naizhuai.R;
import com.naizhuai.ui.components.LabelsView;
import com.naizhuai.ui.components.SingleLabelsView;
import com.naizhuai.ui.entity.LabelBean;
import com.naizhuai.ui.entity.mainbusiness.SlideContentBean;
import com.naizhuai.ui.presenter.SlideLabelsPresenter;
import com.naizhuai.util.ToastCompat;
import com.naizhuai.util.autocomplete.Autocomplete;
import com.naizhuai.util.autocomplete.AutocompleteCallback;
import com.naizhuai.util.autocomplete.AutocompletePresenter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ListSlideLabelsHolderAdapter extends RecyclerView.Adapter<ListSlideLabelsHolderAdapter.ViewHolder>{

    private FragmentActivity mActivity;
    private List<SlideContentBean> slideContentList;
    private OnItemClickListener mItemClickListener;

    private SparseArray<LabelBean> labelBeanMap;

    public ListSlideLabelsHolderAdapter(FragmentActivity mActivity, List<SlideContentBean> slideFieldList) {
        this.mActivity = mActivity;
        this.slideContentList=slideFieldList;
        labelBeanMap=new SparseArray<>();
        createUserDetails();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent , int viewType) {
        LayoutInflater mInflater = LayoutInflater.from(parent.getContext());
        View sView = mInflater.inflate(R.layout.adapter_slide_list, parent, false);
        return new ViewHolder(sView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder , int position) {
        List<LabelBean> labelChosen=new ArrayList<>();
        slideContentList.get(position).setLabelChosen(labelChosen);
        Glide.with(mActivity).load(slideContentList.get(position).getFieldUrl()).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(holder.fieldImg);
        holder.fieldTitle.setText(slideContentList.get(position).getFieldTitle());
//        holder.labelExa.setLabels(slideContentList.get(position).getLabelBeans(), new LabelsView.LabelTextProvider<LabelBean>() {
//            @Override
//            public CharSequence getLabelText(TextView label, int position, LabelBean data) {
//                return data.getName();
//            }
//        });
        initViewListener(holder,slideContentList.get(position).getLabelChosen(),slideContentList.get(position).getLabelBeans(),position);
    }

    private void initViewListener(ViewHolder holder,List<LabelBean> labelChosen,List<LabelBean> labelExams,int position) {
        holder.labelExa.setOnLabelClickListener(null);
        holder.labelChosen.setOnLabelClickListener(null);
        setupUserAutocomplete(holder.labelInput,position);
        holder.labelCommit.setOnClickListener(new FiledCommitListener(holder.labelChosen,holder.labelInput,labelChosen,position));
        holder.labelExa.setOnLabelSelectChangeListener(new LabelSelectChangeListener(labelChosen,holder.labelChosen));
        holder.labelChosen.setOnLabelClickListener(new LabelItemClickListener(holder.labelChosen,labelChosen,labelExams,holder.labelExa));
    }

    private void notifyDataChangedLabel(LabelsView labels,List<LabelBean> beanList){
//        labels.setLabels(beanList, new LabelsView.LabelTextProvider<LabelBean>() {
//            @Override
//            public CharSequence getLabelText(TextView label, int position, LabelBean data) {
//                return data.getName();
//            }
//        });
    }


    private void setupUserAutocomplete(EditText edit,int position) {
        float elevation = 6f;
        Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
        AutocompletePresenter<LabelBean> presenter = new SlideLabelsPresenter(mActivity);
        AutocompleteCallback<LabelBean> callback = new AutocompleteCallback<LabelBean>() {
            @Override
            public boolean onPopupItemClicked(Editable editable, LabelBean item) {
                labelBeanMap.remove(position);
                editable.clear();
                editable.append(item.getName());
                item.setType(LabelBean.TYPE_USE_SYSTEM);
                labelBeanMap.put(position,item);
                return true;
            }

            public void onPopupVisibilityChanged(boolean shown) {}
        };

        Autocomplete<LabelBean> userAutocomplete;
        userAutocomplete = Autocomplete.<LabelBean>on(edit)
                .with(elevation)
                .with(backgroundDrawable)
                .with(presenter)
                .with(callback)
                .build();
    }

    public List<LabelBean> getChosenLabel(){
        List<LabelBean> beansChosenList=new ArrayList<>();
        for (SlideContentBean content:slideContentList) {
            beansChosenList.addAll(content.getLabelChosen());
        }
        return beansChosenList;
    }

    public class LabelItemClickListener implements LabelsView.OnLabelClickListener{

        private LabelsView labelViewChosen;
        private LabelsView labelViewExam;
        private List<LabelBean> labelChosenList;
        private List<LabelBean> labelExamList;

        public LabelItemClickListener(LabelsView labelViewChosen,List<LabelBean> labelChosenList,List<LabelBean> labelExamList,LabelsView labelViewExam) {
            this.labelViewChosen = labelViewChosen;
            this.labelChosenList=labelChosenList;
            this.labelExamList=labelExamList;
            this.labelViewExam=labelViewExam;
        }

//        @Override
//        public void onLabelClick(TextView label, Object data, int position) {
//            labelChosenList.remove(position);
//            LabelBean bean= (LabelBean) data;
//            for (int index=0;index<labelExamList.size();index++){
//                if(bean.getName().equalsIgnoreCase(labelExamList.get(index).getName())){
//                    if (( labelViewExam.getChildAt(index).isSelected()))
//                        labelViewExam.getChildAt(index).setSelected(false);
//                    break;
//                }
//            }
//            notifyDataChangedLabel(labelViewChosen,labelChosenList);
//        }

        @Override
        public void onLabelClick(SingleLabelsView label, Object data, int position) {

        }
    }



    public class LabelSelectChangeListener implements LabelsView.OnLabelSelectChangeListener {

        private List<LabelBean> labelChosenList;
        private LabelsView labelsViewChosen;

        public LabelSelectChangeListener(List<LabelBean> labelChosenList, LabelsView labelsViewChosen) {
            this.labelChosenList = labelChosenList;
            this.labelsViewChosen = labelsViewChosen;
        }

        @Override
        public void onLabelSelectChange(SingleLabelsView label, Object data, boolean isSelect, int position) {
            LabelBean bean= (LabelBean) data;
            bean.setType(LabelBean.TYPE_USE_SYSTEM);
            if(isSelect){
                boolean contain=false;
                for (LabelBean lab:labelChosenList) {
                    if(lab.getName().contains(bean.getName().trim())){
                        contain=true;
                        break;
                    }
                }
                if(contain)
                    ToastCompat.showToast(mActivity, mActivity.getResources().getText(R.string.label_has_exist), Toast.LENGTH_SHORT);
                else{
                    labelChosenList.add(bean);
                    notifyDataChangedLabel(labelsViewChosen,labelChosenList);
                }
            }else{
                for (int index=0;index<labelChosenList.size();index++){
                    if(labelChosenList.get(index).getName().equals(bean.getName().trim())){
                        labelChosenList.remove(index);
                        break;
                    }
                }
                notifyDataChangedLabel(labelsViewChosen,labelChosenList);
            }
        }
    }


    public class FiledCommitListener implements View.OnClickListener{
        private EditText editText;
        private List<LabelBean> labelChosenList;
        private LabelsView labelsView;
        private int position;

        public FiledCommitListener(LabelsView labelsViewChosen,EditText editText,List<LabelBean> labelChosenList,int position) {
            this.editText = editText;
            this.labelChosenList=labelChosenList;
            this.labelsView=labelsViewChosen;
            this.position=position;
        }

        @Override
        public void onClick(View v) {
            String edit_txt=editText.getText().toString();
            if(edit_txt.equals(""))
                return;
            boolean contain=false;
            for (LabelBean label:labelChosenList) {
                if(label.getName().contains(edit_txt.trim())){
                    contain=true;
                    break;
                }
            }
            if(contain)
                ToastCompat.showToast(mActivity,mActivity.getResources().getText(R.string.label_has_exist),Toast.LENGTH_SHORT);
            else{
                LabelBean editBean=labelBeanMap.get(position);
                if(editBean==null)
                    labelChosenList.add(new LabelBean(LabelBean.TYPE_SELF_SYSTEM,edit_txt));
                else
                    labelChosenList.add(editBean);
                notifyDataChangedLabel(labelsView,labelChosenList);
            }
            editText.setText("");
        }
    }

    @Override
    public int getItemCount() {
        return slideContentList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView fieldTitle;
        ImageView fieldImg;
        EditText labelInput;
        Button labelCommit;
        LabelsView labelExa,labelChosen;


        public ViewHolder(View view) {
            super(view);
            fieldTitle = (TextView) view.findViewById(R.id.field_selected_title);
            fieldImg = (ImageView) view.findViewById(R.id.field_selected_img);
            labelInput = (EditText) view.findViewById(R.id.field_selected_commit_txt);
            labelCommit = (Button) view.findViewById(R.id.field_selected_commit_btn);
            labelExa = (LabelsView) view.findViewById(R.id.labels_example);
            labelChosen = (LabelsView) view.findViewById(R.id.labels_chosen);
//            view.setOnClickListener(this);
        }
    }


    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mItemClickListener = mItemClickListener;
    }



    /* ==========This Part is not necessary========= */

    /**
     * Create Random Users
     */
    private void createUserDetails() {

    }

    /*
     * Snippet from http://stackoverflow.com/a/363692/1008278
     */
    public static int randInt(int min , int max) {
        final Random rand = new Random();
        return rand.nextInt((max - min) + 1) + min;
    }

    /* ==========This Part is not necessary========= */

}
